using HCore.Core;
using HCore.Unity.Core;
using UnityEngine;

namespace HCore.Tests.Runtime.HeatMapGrid
{
    public class HeatMapVisual : MonoBehaviour
    {
        private bool isUpdateMesh;
        private Grid2D<HeatMapGridObject> mGrid;
        private Mesh mMesh;

        private void Awake()
        {
            mMesh = new Mesh();
            GetComponent<MeshFilter>().mesh = mMesh;
        }

        private void LateUpdate()
        {
            if (isUpdateMesh)
            {
                isUpdateMesh = false;
                UpdateHeatMapVisual();
            }
        }

        public void SetGrid(Grid2D<HeatMapGridObject> grid)
        {
            mGrid = grid;
            UpdateHeatMapVisual();


            mGrid.AddCellChangedListener(_ => isUpdateMesh = true);
        }

        private void UpdateHeatMapVisual()
        {
            // 创建空数据的栅格
            GameUtils.CreateEmptyQuadMeshArrays(
                mGrid.Width * mGrid.Height,
                out var vertices,
                out var uv,
                out var triangles
            );

            // 循环栅格填充数据
            ForUtils.For(mGrid.Width, mGrid.Height, (x, y) =>
            {
                // 当前各自的索引
                var index = x * mGrid.Height + y;
                var quadSize = Vector2.one * mGrid.CellSize;

                var gridObject = mGrid.GetCell(x, y);
                var gridValue = gridObject.GetValueNormalized();
                var gridValueUV = new Vector2(gridValue, 0f);


                GameUtils.AddToMeshArrays(vertices, uv, triangles, index, mGrid.GetCellWorldPosition(x, y) + quadSize * 0.5f, 0f, quadSize, gridValueUV, gridValueUV);
            });

            mMesh.vertices = vertices;
            mMesh.uv = uv;
            mMesh.triangles = triangles;
        }
    }
}